<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/3/15
 * Time: 13:37
 */

namespace app\cls\tom;


use app\lib\cache\SimpleJQREDIS;
use app\lib\db\DB;

class SysResource
{
    private static $sysResources = [];

    /**
     * @param bool $isMaster
     * @return DB
     */
    public static function getDB($isMaster = true)
    {
        if($isMaster){
            $resourceName = "master_db";
        }else{
            $resourceName = "slave_db";
        }
        if(array_key_exists($resourceName,static::$sysResources)){
            return static::$sysResources[$resourceName];
        }
        $db = new DB($isMaster);
        static::$sysResources[$resourceName] = $db;
        return $db;
    }

    /**
     * @return \Redis
     */
    public static function getRedis(){
        $resourceName = "redis";
        if(array_key_exists($resourceName,static::$sysResources)){
            return static::$sysResources[$resourceName];
        }
        $redis = new SimpleJQREDIS(REDIS_HOST,REDIS_PORT);
        static::$sysResources[$resourceName] = $redis;
        return $redis;
    }

    /**
     * shm cache
     * @return Cache|mixed
     */
    public static function getShmCache(){
        $resourceName = "shmCache";
        if(array_key_exists($resourceName,static::$sysResources)){
            return static::$sysResources[$resourceName];
        }
        $cache = new Cache();
        static::$sysResources[$resourceName] = $cache;
        return $cache;
    }

    /**
     * @param $modelName
     * @param bool $isInit
     * @param bool $isMaster
     * @return \app\model\Model ;
     */
    public static function model($modelName,$isInit = true,$isMaster = true)
    {
        $resourceName = "model";
        if(isset(static::$sysResources[$resourceName]) && array_key_exists($modelName,static::$sysResources[$resourceName])){
            return static::$sysResources[$resourceName][$modelName];
        }
        $class = '\\app\\model\\'.$modelName;
        if($isInit){
            $model = new $class(static::getDB($isMaster));
        }else{
            $model = new $class();
        }
        static::$sysResources[$resourceName][$modelName] = $model;
        return $model;
    }
}